package dwz.cms.article.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

/** 
* Created by Eclipse
* @author : Yating
* @version:2017年4月19日 下午2:51:21 
* Request转换成entity 
*/
public final class ParseRequest {
	
	
	public static <T> T parseRequestToEntity(HttpServletRequest request, Class<T> clazz) throws Exception{  
		
		T entity = clazz.newInstance();  
	    Field[] fields = clazz.getDeclaredFields();  
	    for (Field field : fields) {  
	        field.setAccessible(true);  
	        String fieldName = field.getName();  
	        String fieldType = field.getType().getName();  
	        String value = request.getParameter(fieldName);  
	        if(value == null || value.trim().length() == 0){  
//	            if(isFile(fieldName, request)){//是上传文件，并且不为空  
//	                //如果是上传文件，保存并返回可直接访问的html路径  
//	                field.set(entity, saveFile(request, request.getPart(fieldName)));  
//	            }  
	            continue;  
	        }  
	        if(fieldType.equalsIgnoreCase("java.lang.String")){  
	            field.set(entity, value);  
	        }else if(fieldType.equalsIgnoreCase("java.lang.Byte")){ 
//	        	int iValue =Integer.parseInt(value);
//	        	Byte bValue=(byte)iValue;
//	        	field.setByte(entity, bValue); 
	            field.setByte(entity, Byte.valueOf(value));  
	        }else if(fieldType.equalsIgnoreCase("short")){  
	            field.setShort(entity, Short.parseShort(value));  
	        }else if(fieldType.equalsIgnoreCase("java.lang.Integer")){  
	            field.set(entity, Integer.parseInt(value));  
	        }else if(fieldType.equalsIgnoreCase("long")){  
	            field.setLong(entity, Long.parseLong(value));  
	        }else if(fieldType.equalsIgnoreCase("float")){  
	            field.setFloat(entity, Float.parseFloat(value));  
	        }else if(fieldType.equalsIgnoreCase("double")){  
	            field.setDouble(entity, Double.parseDouble(value));  
	        }else if(fieldType.equalsIgnoreCase("boolean")){  
	            field.setBoolean(entity, Boolean.parseBoolean(value));  
	        }else if(fieldType.equalsIgnoreCase("java.util.Date")){ 
	        	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	            field.set(entity, sdf.parse(value));  
	        }else{  
	            field.set(entity, value);  
	        }  
	    }  
	    return entity;  
	}

}
 